<?
ini_set("display_errors",1);
include($_SERVER['DOCUMENT_ROOT'].'/includes/functions.inc.php');
include($_SERVER['DOCUMENT_ROOT'].'/portals/config.php');
include($_SERVER['DOCUMENT_ROOT'].'/groups/database.php');

init_session();

if (empty($_SESSION['user_id'])) {
	include($_SERVER['DOCUMENT_ROOT'].'/portals/login.inc.php');
	exit;
}






$portal_id = $id = intval(@$_GET['id']);



if ($id) {
	$current = getRow("SELECT * FROM portal WHERE portal_id = $id");
	
	if ($current['status_id'] != 1 || $current['user_id'] != $_SESSION['user_id']) {
		die("unable to edit this Portal");
	}
	
} else {
	die("huh?");
}

if (!empty($_GET['callback'])) {
	
	$updates = array();
	$updates['status_id'] = 0;
	$updates['portal_id'] = $portal_id;
	$updates['user_id'] = $_SESSION['user_id'];
	$updates['type'] = $_GET['type'];
	$updates['profile'] = $_GET['profile'];
	$updates['created'] = 'NOW()';
	$sql= updates_to_insert('filter',$updates);
	
	queryExecute($sql);
	
	if (!$filter_id) {
		$filter_id = mysql_insert_id();
	}
	
	$number = getOne("SELECT COUNT(*) FROM filter WHERE portal_id = $id AND status_id IN (0,1)");
	
	if ($number > 20) {
		$text = "<tr><td colspan=4>Max number of filters reached :(</td></tr>";
	} else {
		ob_start();
		outputFilterRow($filter_id,$number,$updates);
		$text = ob_get_clean();
	}
	
	#Get from http://pear.php.net/package/Services_JSON
	require_once $_SERVER['DOCUMENT_ROOT'].'/google/JSON.php';
	$json = new Services_JSON();
	
	echo he($_GET['callback'])."(";
	print $json->encode($text);
	echo ");";
	exit;
}



include($_SERVER['DOCUMENT_ROOT'].'/portals/header.inc.php');

print "<h3>Define Filters for <a href=\"portal.php?id=$id\">".he($current['title'])."</a> Portal</h3>";

if (!empty($_POST)) {

	
	


	
	if (!empty($_POST['title'])) {
		$user_id = $_SESSION['user_id']?$_SESSION['user_id']:1;
		
		foreach ($_POST['title'] as $filter_id => $title) {
		
			$updates = array();
		
			
			$updates['title'] = $title;
			#TODO $updates['profile'] = $_POST['profile'][$filter_id];
			$updates['value'] = trim($_POST['value'][$filter_id]);
			
			if ($_POST['profile'][$filter_id] == 'ids') {
				$updates['value'] = trim(preg_replace('/[^\d]+/',' ',$updates['value']));
			}//todo also clean up words and sphinx?
			
			$current_filter = getRow("SELECT * FROM filter WHERE portal_id = $id AND filter_id = $filter_id");
			if (empty($current_filter)) {
				die("oh dear oh dear....");
			}
			foreach ($updates as $key => $value) {
				if ($value == $current_filter[$key]) 
					unset($updates[$key]);
			}
			if (!empty($_POST['delete'][$filter_id])) 
				$updates['status_id'] = 4;
				
			if (!empty($updates)) {

				if ($filter_id) {
					if ($current_filter['status_id'] == 0 && empty($updates['status_id']))
						$updates['status_id'] = 1;
						
					$updates['last_run'] = 0;
					$sql= updates_to_update('filter',$updates,'filter_id',$filter_id);
				} else {
					$updates['portal_id'] = $portal_id;
					$updates['user_id'] = $_SESSION['user_id'];
					$updates['created'] = 'NOW()';
					$sql= updates_to_insert('filter',$updates);
				}

				queryExecute($sql);

				if (!$filter_id) {
					$filter_id = mysql_insert_id();
				}
			

				//log the updates
				foreach ($updates as $key => $value) {
					if (!is_null($value) && $key != 'last_run') {
						$u = array();
						$u['table'] = 'filter';
						$u['table_id'] = $filter_id;
						$u['name'] = $key;
						$u['value'] = $value;
						$u['user_id'] = $user_id;
						$sql= updates_to_insert('update_log',$u);
						queryExecute($sql);
					}
				}
			}
		}

		
		
		print "<p>Updates Saved. Thank you</p>";

		print "<p><a href=\"portal.php?id=$id\">View Portal Page</a></p>";

		if (empty($_POST['toall']) && empty($_POST['toany'])) {
?>

<div style="background-color:pink;padding:10px">
	NOTE: It can take a few minutes for images to begin populating a new portal once the filters have been defined. In addition changing the filters for the moment wont update the images in the portal very quickly. See the 
<a href="faq.php">FAQ</a>.
</div>


<form name="redirect">
<p>You will be automatically redirected in <input type="text" size="3" name="seconds"> seconds.</p>
</form>
<script>
var destiniation="portal.php?id=<? echo $id; ?>";
var start=5;
var current=document.forms['redirect'].seconds.value=start+1
function redirectTick() {
	if (current==1) {
		window.location=destiniation;
		return;
	} else{
		current-=1;
		document.forms['redirect'].seconds.value=current;
		setTimeout("redirectTick()",1000);
	}	
}
redirectTick();
</script>
<?
			exit;
		} else {
			if (!empty($_POST['toall'])) {
				$data = getCol("SELECT filter_id FROM filter WHERE type='any' AND portal_id = $id AND status_id = 1");
				if ($data) {
					foreach ($data as $filter_id) {
						$u = array();
						$u['table'] = 'filter';
						$u['table_id'] = $filter_id;
						$u['name'] = 'type';
						$u['value'] = 'all';
						$u['user_id'] = $user_id;
						$sql= updates_to_insert('update_log',$u);
						queryExecute($sql);
					}
					queryExecute("UPDATE filter SET type='all' WHERE type='any' AND portal_id = $id AND status_id = 1");
				}
				$data = getCol("SELECT filter_id FROM filter WHERE profile in ('gurl','ids') AND portal_id = $id AND status_id = 1");
				if ($data) {
					foreach ($data as $filter_id) {
						$u = array();
						$u['table'] = 'filter';
						$u['table_id'] = $filter_id;
						$u['name'] = 'status_id';
						$u['value'] = 4;
						$u['user_id'] = $user_id;
						$sql= updates_to_insert('update_log',$u);
						queryExecute($sql);
					}
					queryExecute("UPDATE filter SET status_id = 4 WHERE profile in ('gurl','ids') AND portal_id = $id AND status_id = 1");
				}
				
			} elseif (!empty($_POST['toany'])) {
				$data = getCol("SELECT filter_id FROM filter WHERE type='all' AND portal_id = $id AND status_id = 1");
				if ($data) {
					foreach ($data as $filter_id) {
						$u = array();
						$u['table'] = 'filter';
						$u['table_id'] = $filter_id;
						$u['name'] = 'type';
						$u['value'] = 'any';
						$u['user_id'] = $user_id;
						$sql= updates_to_insert('update_log',$u);
						queryExecute($sql);
					}
					queryExecute("UPDATE filter SET type='any' WHERE type='all' AND portal_id = $id AND status_id = 1");
				}
				//todo - delete 'all' filters that dont work as 'any' 
			} 


		}

	}

}


?>

<form method="post" name="theForm">

<div style="font-size:0.8em">Note, that during this alpha stage most portals will display at most about 1,000 images, picked at random from the full selection. But even after launch portals are expected to work best if aim to have under about 10,000 images. </div>


<h2>Only include images in this portal if ...</h2>

<?

$data = getAll("SELECT * FROM filter WHERE portal_id = $id AND status_id = 1 ORDER BY type+0,filter_id");
	

$last = -1;
$stats = array();

if (!empty($data)) {
	if ($data[0]['type'] == 'not') {
		//if none, need an any!
		
		if (isset($_POST['toall'])) {
			outputHeader($last = 'all');
		} else {
			outputHeader($last = 'any');
			
		}
		$stats[$last] = 1;//hack to get the swap button to appear
	}
	foreach ($data as $idx => $row) {
		if ($row['type'] != $last) {
			if ($last > -1) {
				 outputFooter($last,$row);
			}

			outputHeader($last = $row['type']);

		} 

		$filter_id = $row['filter_id'];

		outputFilterRow($filter_id,($idx+1),$row);

		@$stats[$row['type']][$row['profile']]++;
	}
}

if ($last > -1 && $last != 'not') {
	outputFooter($last);
	
	//if an any, need a blank not. 
	outputHeader($last = 'not');
 
} elseif ($last == -1) {
	//if none, need an any!
	
	if (isset($_POST['toall'])) {
		outputHeader($last = 'all');
	} else {
		outputHeader($last = 'any');
	}
}

if ($last > -1) {
	//finish off the open one.
	 outputFooter($last,$row);
}	

?>
<div style="margin-top:20px">
<input type="submit" name="save" value="Submit Changes"/>  
</div>

<?

if ((isset($stats['any']) || empty($stats)) && empty($_POST['toall'])) {
	?>
	<br/><br/>
	<div class=important>
	<input type=submit name=toall value="Convert this Portal to use 'ALL' filters" onclick="return confirm('Please confirm (remember some filters might be deleted and all will need checking work as intended):');"/> <b>NOTE: All 'List of Images' and/or 'Collection' filters will be DELETED</b>, all others will be converted to 'AND'.<br/>
	This is a temporally solution as we currently can't easily support a portal containing both 'any' and 'all' filters.
	</div>
	<?
} elseif (isset($stats['all']) || empty($stats)) {
	?>
	<br/><br/>
	<div class=important>
	<input type=submit name=toany value="Convert this Portal to use 'ANY' filters" onclick="return confirm('Please confirm (You should carefully check the new filters to ensure the working as intended):');"/> NOTE: The 'ALL' filters will be converted to 'ANY'.<br/>
	This is a temporally solution as we currently can't easily support a portal containing both 'any' and 'all' filters.
	</div>
	<?
}

?>





</form>

or <a href="portal.php?id=<? echo $id; ?>" onclick="return confirm('Are you sure?');">Return to listing</a> (without saving changes)

<script src="http://www.google.com/jsapi"></script>
<script>
  // Load jQuery
  google.load("jquery", "1");

  function addNewFilter(that,portal_id,type) {
    
    var ele = that.form.elements['add_profile['+type+']'];
    
    var profile = ele.options[ele.selectedIndex].value;
    
    $.getJSON("?id="+portal_id+"&type="+type+"&profile="+profile+"&callback=?",

      // on search completion, process the results
      function (data) {
	if (data) {
		$("#row-"+type).before(data);
        }
        
      });
   }
   
   function deleteFilter(filter_id) {
   	if (!filter_id)
   		return;
   	
   	if (!confirm("Are you sure you wish to delete this filter?"))
   		return;
   	
   	var f = document.forms['theForm'];
   	
   	f.elements['delete['+filter_id+']'].checked = true;
   	
   	document.getElementById('header'+filter_id).style.display='none';
   	document.getElementById('row'+filter_id).style.display='none';
   	
   }
   
</script>   


<?

include($_SERVER['DOCUMENT_ROOT'].'/portals/footer.inc.php');

##
########################################################################
##

function outputHeader($type) {
	print "<h3>...";
	switch($type) {
		case 'any': print "match ANY of these filters:"; break;
		case 'all': print "matched by ALL of these filters:"; break;
		case 'not': print "but EXCLUDE images that match any/all of these:"; break;
	}
	print "</h3>";

	print "<table class=\"filtertable\">";
}

function outputFilterRow($filter_id,$number,$row) {
	global $profiles,$id;
	
	print "<tr id=\"header$filter_id\">";
	print "<td colspan=\"3\" class=\"filterheader\">Filter ".($number).". ";
	if (1) {
		if ($row['type'] == 'not' || getOne("SELECT count(*) FROM filter WHERE portal_id = $id AND status_id IN (0,1) AND filter_id != $filter_id AND `type` = ".dbQuote($row['type']))) { 
			switch($row['type']) {
				case 'any': print "or "; break;
				case 'all': print "and "; break;
				case 'not': print "exclude this "; break;
			}
		}
		print "<b>".$profiles[$row['profile']]."</b>";
	} else {
		$keys = array_keys($profiles);
		$selected = array_search($row['profile'],$keys);
		print "<select name=\"profile[$filter_id]\" onchange=\"this.selectedIndex=$selected\" style=\"color:gray\">";
		foreach ($profiles as $value => $name) {
			printf("<option value=\"%s\"%s>%s</option>",$value,$row['profile']==$value?' selected':'',$name);
		}
		print "</select><span class=\"helpinfo\">Currently unchangable</span>";
	}
	print "</td>";
	print "<td class=\"filterheader\"><a href=\"javascript:void(deleteFilter($filter_id));\" class=\"delete\">Delete this filter</a><input type=checkbox name=\"delete[$filter_id]\" style=\"display:none\"/></td>";
	print "</tr>";
	
	print "<tr id=\"row$filter_id\">";
	print "<td>".($number).".</td>";
	print "<td valign=\"top\">Optional Title:<br/>";
	print "<input type=\"text\" name=\"title[$filter_id]\" value=\"".he($row['title'])."\" maxlength=32 size=26 />";
	print "<div class=\"helpinfo\">(your reference only)</div>";
	print "</td>";
	print "<td valign=\"top\"><b>Value</b>:<br/>";
	
	$inclusion = ($row['type'] == 'not')?'excluded':'included';
	switch($row['profile']) {
		case 'gurl':
			print "<input type=\"text\" name=\"value[$filter_id]\" value=\"".he($row['value'])."\" maxlength=\"255\" size=\"90\"/>";
			print "<div class=\"helpinfo\">A URL of a <b>Article, Gallery, Themed Topic or Shared Description</b> on Geograph, (includes images from all pages if multiple). Examples:<br><tt>http://www.geograph.org.uk/gallery/hills_6927</tt><br><tt>http://www.geograph.org.uk/article/Shepherd-Neame</tt><br><tt>http://www.geograph.org.uk/discuss/?action=vthread&forum=6&topic=1696</tt><br><tt>http://www.geograph.org.uk/snippet/1234</tt><br/>Does not work with search results, or any other Geograph page</div>";
			break;
		case 'ids':
			print "<textarea name=\"value[$filter_id]\" rows=\"4\" cols=\"70\">".he($row['value'])."</textarea>";
			print "<div class=\"helpinfo\">A simple list of Image IDs, seperated by comma or spaces, don't worry about duplicates.<br/>(also can also paste in numbers with brackets [[[23356]]] [[[324234]]] etc)</div>";
			break;
		case 'sphinx':
			print "<input type=\"text\" name=\"value[$filter_id]\" value=\"".he($row['value'])."\" maxlength=\"255\" size=\"90\"/>";
			print "<div class=\"helpinfo\">Search Query - Supports the full <a href=\"http://www.geograph.org.uk/article/Word-Searching-on-Geograph\" target=\"_blank\">Word Searching on Geograph</a> syntax.<br/> Example: <tt>trig | (os pillar) | trigpoint | triangulation</tt></div>";
			print "<div class=\"helpinfo\">Keywords match against the title, description, category, photographer name, shared description(s), taken date (<tt>2001</tt>, <tt>199412</tt>, <tt>19811012</tt> or <tt>April</tt>) and subject grid reference (<tt>NT4567</tt>, <tt>J45</tt> or <tt>TQ</tt>)</div>";
			break;
		case 'title':
		case 'text':
		case 'snippet':
		case 'category':
			print "<input type=\"text\" name=\"value[$filter_id]\" value=\"".he($row['value'])."\" maxlength=\"255\" size=\"90\"/>";
			print "<div class=\"helpinfo\">Matches Keywords in the specific fields only. Supports phrases, excluded words and the OR keyword, skip stemming etc.</div>";
			break;
		case 'phrase':
			print "<input type=\"text\" name=\"value[$filter_id]\" value=\"".he($row['value'])."\" maxlength=\"255\" size=\"90\"/>";
			print "<div class=\"helpinfo\">One single phrase - no special syntax. Subject to stemming</div>";
			
			break;
		case 'words':
			print "<input type=\"text\" name=\"value[$filter_id]\" value=\"".he($row['value'])."\" maxlength=\"255\" size=\"90\"/>";
			print "<div class=\"helpinfo\">Seperate words with spaces - otherwise no special syntax. Subject to stemming</div>";
			
			break;
		case 'grs':
			print "<textarea name=\"value[$filter_id]\" rows=\"3\" cols=\"70\">".he($row['value'])."</textarea>";
			print "<div class=\"helpinfo\">List of Grid References seperated by spaces. Photos in any of these square(s) will be $inclusion.<br/> 4-Figure (eg <b>SH1234</b>), Hectad (eg <b>H70</b>) or Myriad (eg <b>NT</b>) works.</div>";
			break;
		case 'taken':
			print "<textarea name=\"value[$filter_id]\" rows=\"3\" cols=\"70\">".he($row['value'])."</textarea>";
			print "<div class=\"helpinfo\">List of dates seperated by spaces. Photos taken during these date(s) will be $inclusion.<br/> Day (eg <b>20100318</b>), Month (eg <b>199505</b>) or Year (eg <b>2001</b>) works.</div>";
			break;
		case 'users':
			print "<textarea name=\"value[$filter_id]\" rows=\"3\" cols=\"70\">".he($row['value'])."</textarea>";
			print "<div class=\"helpinfo\">List of user ID's seperated by spaces. Photos contributed by these user(s) will be $inclusion.<br/> Find the ID from Profile pages, eg user at http://www.geograph.org.uk/profile/1234 has an ID of <b>1234</b>. <a href=\"http://www.geograph.org.uk/finder/contributors.php\" target=_blank>Contributor Search</a> may be useful.</div>";
			break;
		case 'shared':
			print "<textarea name=\"value[$filter_id]\" rows=\"3\" cols=\"70\">".he($row['value'])."</textarea>";
			print "<div class=\"helpinfo\">List of Shared Description ID's seperated by spaces. Photos using any of these Shared description(s) will be $inclusion.<br/> Find the ID from Shared Description pages, eg at http://www.geograph.org.uk/snippet/1234 has an ID of <b>1234</b>. <a href=\"http://www.geograph.org.uk/snippets.php\" target=_blank>Shared Description Search</a> may be useful.</div>";
			break;
		default: 
			print "<b>Umm, unknown filter!</b>";
	}
	
	if ($row['type'] == 'not' && $row['profile'] != 'ids') {
		print "<div class=\"helpinfo\">NOTE: <b>Will not <u>not</u> exclude images specifically added via ID or from a Collection</b></div>";	
	}
	
	print "</td>";
	if ($row['profile'] == 'sphinx') {
		print "<td>";
		print "<input type=button value=Test onclick=\"window.open('http://www.geograph.org.uk/search.php?searchtext='+encodeURI(this.form.elements['value[$filter_id]'].value)+'&amp;do=1')\"/>";
		print "</td>";
	} elseif ($row['profile'] == 'text' || $row['profile'] == 'title' || $row['profile'] == 'snippet' || $row['profile'] == 'category') {
		print "<td>";
		print "<input type=button value=Test onclick=\"window.open('http://www.geograph.org.uk/search.php?searchtext={$row['profile']}:'+encodeURI(this.form.elements['value[$filter_id]'].value)+'&amp;do=1')\"/>";
		print "</td>";
	} elseif ($row['profile'] == 'grs' || $row['profile'] == 'taken' || $row['profile'] == 'users') {
		$prefix = ($row['profile'] == 'users')?'user_id:':'';
		print "<td>";
		print "<input type=button value=Test onclick=\"window.open('http://www.geograph.org.uk/search.php?searchtext=$prefix('+encodeURI(this.form.elements['value[$filter_id]'].value.replace(/ /g,'|'))+')&amp;do=1')\"/>";
		print "</td>";
	}
	print "</tr>";

}

function outputFooter($type) {
	global $portal_id;
	print "<tr id=\"row-$type\">";
	print "<td colspan=\"4\" class=\"filterheader\">Add new $type filter: ";
	print "<select name=\"add_profile[$type]\">";
	foreach ($GLOBALS['profiles_'.$type] as $value => $name) {
		printf("<option value=\"%s\"%s>%s</option>",$value,'',$name);
	}
	print "</select>";
	print "<input type=button name=\"add[$type]\" value=\"Add\" onclick=\"addNewFilter(this,$portal_id,'$type')\"/>";
	print "</td>";
	print "</tr>";

	print "</table>";
}


